package com.ytktt.study.week3.task346.gateway.inbound;

import com.ytktt.study.week3.task346.gateway.properties.ApplicationProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Data
@Component
@RequiredArgsConstructor
public class HttpInboundServer {

    private final ApplicationProperties applicationProperties;
    private final HttpInboundInitializer httpInboundInitializer;

    public void run(int port) throws Exception {
        ApplicationProperties.InBoundProperties inBound = this.applicationProperties.getInBound();

        EventLoopGroup bossGroup = new NioEventLoopGroup(inBound.getBossCount());
        EventLoopGroup workerGroup = new NioEventLoopGroup(inBound.getWorkerCount());

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.TCP_NODELAY, inBound.isTcpNoDelay())
                    .childOption(ChannelOption.SO_KEEPALIVE, inBound.isKeepalived())
                    .childOption(ChannelOption.SO_REUSEADDR, inBound.isReuseAddr())
                    .childOption(ChannelOption.SO_RCVBUF, inBound.getRcvBuf() * 1024)
                    .childOption(ChannelOption.SO_SNDBUF, inBound.getBossCount() * 1024)
                    .childOption(EpollChannelOption.SO_REUSEPORT, inBound.isReusePort())
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(this.httpInboundInitializer);

            Channel ch = b.bind(port).sync().channel();
            log.info("开启netty http服务器，监听地址和端口为 http://127.0.0.1:{}/", port);
            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
